import { HttpException, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Role } from '../role/entities/role.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>
  ) { }
  async register(data) {
    const existUser = await this.userRepository.findOne({ where: { username: data.username } })
    if (existUser) {

      throw new HttpException("用户名已存在", 400);
    }
    const newUser = this.userRepository.create(data)
    return await this.userRepository.save(newUser)
  }
  async create(data) {
    const existUser = await this.userRepository.findOne({ where: { username: data.username } })
    if (existUser) {
      throw new HttpException("用户名已存在", 400);
    }
    const newUser = this.userRepository.create(data)
    return await this.userRepository.save(newUser)
  }

  async findUserPermission(userId: string) {
    console.log(userId);    
    const userPermission = await this.userRepository.findOne({
      where: {
        id: userId
      },
      relations: ['roles.menu.permission']
    })
    console.log(userPermission);    
    return userPermission
  }

  async update(data) {
    const res = await this.userRepository.update(data.id, data)
    return res
  }
  queryAll() {
    return this.userRepository.find()
  }

  remove(data) {
    return this.userRepository.delete({ id: data.id })
  }

  updateUserRole(data) {
    console.log(data);
    data.roles = data.roles.map((id) => {
      return Object.assign(new Role(), { id: id })
    })
    console.log(data);
    const res = this.userRepository.save(data)
    return {}
  }

}
